package org.pearl.springbootsecurity.demo.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.pearl.springbootsecurity.demo.config.RedisUtil;
import org.pearl.springbootsecurity.demo.dao.UserMapper;
import org.pearl.springbootsecurity.demo.entity.Permission;
import org.pearl.springbootsecurity.demo.entity.Role;
import org.pearl.springbootsecurity.demo.pojo.UserInfoDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by TD on 2021/8/16
 * 登录成功处理器
 */
@Component
@Slf4j
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    UserMapper userMapper;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 1. 获取登录名
        String username = authentication.getName();
        // 2. 查询用户的权限信息保存到Redis中
        UserInfoDO userInfoDO = userMapper.getUserInfoByUserName(username);
        // 3. 将角色和权限信息封装为Security需要的GrantedAuthority集合
        List<GrantedAuthority> authList = new ArrayList<>();
        // 4. 循环添加权限值
        if (userInfoDO==null){
            // 6. 返回登录成功Json 给前端
            response.setStatus(HttpStatus.OK.value());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("msg", "登录成功");
            result.put("username", username);
            result.put("userInfo", authentication);
            objectMapper.writeValue(response.getOutputStream(), result);
        }

        List<Permission> permissionList = userInfoDO.getPermissionList();
        if (permissionList != null && permissionList.size() > 0) {
            for (Permission permission : permissionList) {
                String code = permission.getCode();// 权限值
                authList.add(new SimpleGrantedAuthority(code));
            }
        }
        // 4. 循环添加权限值
        List<Role> roleList = userInfoDO.getRoleList();
        if (roleList != null && roleList.size() > 0) {
            for (Role role : roleList) {
                String code = role.getRoleCode();// 权限值
                authList.add(new SimpleGrantedAuthority(code));
            }
        }
        // 5. 存入REDIS ,用户名为Key ,权限值列表为值
        RedisUtil.setList(username, authList);
        log.info("=============" + username + "权限已存入到Redis中");

        // 6. 返回登录成功Json 给前端
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "登录成功");
        result.put("username", username);
        result.put("userInfo", authentication);
        objectMapper.writeValue(response.getOutputStream(), result);
    }
}
